class CustomEncryption {
    static FIXED_LENGTH = 5; // 每个字符转译后的固定长度

    static encrypt(plaintext) {
        let ciphertext = '';
        for (const c of plaintext) {
            const encodedChar = this.encodeChar(c);
            ciphertext += encodedChar;
        }
        return ciphertext;
    }

    static decrypt(ciphertext) {
        let plaintext = '';
        for (let i = 0; i < ciphertext.length;) {
            try {
                const encodedChar = ciphertext.substring(i, Math.min(i + this.FIXED_LENGTH, ciphertext.length));
                plaintext += this.decodeChar(encodedChar);
                i += this.FIXED_LENGTH;
            } catch (e) {
                const encodedChar = ciphertext.substring(i, i + 1);
                plaintext += encodedChar;
                i += 1;
            }
        }
        return plaintext;
    }

    static encodeChar(c) {
        // 使用Unicode码点进行转译
        return '§' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
    }

    static decodeChar(encodedChar) {

        if (!encodedChar.startsWith('§')) {
            throw new Error('加密');
        }
        encodedChar = encodedChar.replace('§', '');
        // 解码转译后的Unicode码点
        const decodedValue = parseInt(encodedChar, 16);
        return String.fromCharCode(decodedValue);
    }
}

function highlightText(originalText, replaceWords, color) {

    let encryptedText = CustomEncryption.encrypt(originalText);
    const result = {
        num: 0,
        text: originalText
    }
    for (const data of replaceWords) {
        // const originalWord = data.originalWord;
        // const substituteWord = !data.originalWord ? `$&` : data.originalWord;
        const encryptedWord = CustomEncryption.encrypt(data);
        if (encryptedText.match(new RegExp(encryptedWord, "i"))) {
            result.num ++;
            encryptedText = encryptedText.replace(new RegExp(encryptedWord, 'gi'), `<span style="color:${color};text-decoration: underline;font-weight: bold">$&</span>`)
        }
    }
    if (result.num > 0) {
        result.text = CustomEncryption.decrypt(encryptedText)
    }
    return result;
}

export default {
    highlightText
}

// 示例用法
// const originalText = "李明在浙江的阿里巴巴公司工作了2个月，在浙江参与过电商平台，云计算等开发。以下是他的个人信息：13712345678，330682199508194567，liming123@qq.com";
// const dataList = [
//     { originalWord: "李明", substituteWord: "人名1" },
//     { originalWord: "color", substituteWord: "color1" },
//     { originalWord: "阿里巴巴公司", substituteWord: "公司名1" },
//     { originalWord: "电商平台", substituteWord: "项目名1" },
//     { originalWord: "云计算", substituteWord: "项目名2" },
//     { originalWord: "13712345678", substituteWord: "手机号1" },
//     { originalWord: "330682199508194567", substituteWord: "身份证号1" },
//     { originalWord: "liming123@qq.com", substituteWord: "邮箱1" }
// ];
//
// const highlightedText = highlightText(originalText, dataList, "black");
// console.log("解码后的字符串: " + JSON.stringify(highlightedText));